package com.example.teacherservice.controller;

import com.example.teacherservice.JwtTokenProvider;
import com.example.teacherservice.dto.ApiResponse;
import com.example.teacherservice.dto.LoginRequest;
import com.example.teacherservice.dto.UserInfoResponse;
import com.example.teacherservice.entity.User;
import com.example.teacherservice.service.UserService;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/auth")
public class AuthController {

    @Autowired
    private UserService userService;

    @Autowired
    private JwtTokenProvider jwtTokenProvider;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @PostMapping("/login")
    public ResponseEntity<?> login(@RequestBody LoginRequest loginRequest) {
        // 验证用户类型
        if (!"student".equals(loginRequest.getUserType()) && !"teacher".equals(loginRequest.getUserType())) {
            return ResponseEntity.badRequest().body(new ApiResponse(false, "无效的用户类型"));
        }

        // 查询用户
        User user = userService.findByUsername(loginRequest.getUsername());
        if (user == null || user.getDeleted() == 1) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
                    .body(new ApiResponse(false, "用户名或密码错误"));
        }

        // 验证密码（兼容明文和加密密码）
        boolean passwordValid = loginRequest.getPassword().equals(user.getPassword()) ||
                passwordEncoder.matches(loginRequest.getPassword(), user.getPassword());

        if (!passwordValid) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
                    .body(new ApiResponse(false, "用户名或密码错误"));
        }

        // 验证用户角色（根据图片中role=0是教师）
        boolean isStudent = "student".equals(loginRequest.getUserType()) && user.getRole() == 1;
        boolean isTeacher = "teacher".equals(loginRequest.getUserType()) && user.getRole() == 0;

        if (!isStudent && !isTeacher) {
            return ResponseEntity.status(HttpStatus.FORBIDDEN)
                    .body(new ApiResponse(false, "用户类型与角色不匹配"));
        }

        // 生成JWT令牌
        String token = jwtTokenProvider.generateToken(user.getId(), user.getUsername(), loginRequest.getUserType());

        // 构建响应
        Map<String, Object> response = new HashMap<>();
        response.put("token", token);
        response.put("userId", user.getId()); // 直接使用userId作为键
        response.put("userInfo", new UserInfoResponse(
                "student".equals(loginRequest.getUserType()) ?
                        String.format("2023%04d", user.getId()) :
                        String.format("T%04d", user.getId()),
                user.getUsername(),
                user.getRole(),
                user.getPic()
        ));
        response.put("userType", loginRequest.getUserType());

        return ResponseEntity.ok(new ApiResponse(true, "登录成功", response));
    }

    @PostMapping("/logout")
    public ResponseEntity<?> logout(HttpServletRequest request) {
        // 1. 获取并验证token
        String token = jwtTokenProvider.resolveToken(request);
        if (token != null && jwtTokenProvider.validateToken(token)) {
            // 2. 可以将token加入黑名单（需要实现）
            // jwtTokenProvider.invalidateToken(token);

            // 3. 记录日志等操作
            Long userId = jwtTokenProvider.getUserIdFromToken(token);
            System.out.println("用户ID "+userId+"已退出登录");
        }

        return ResponseEntity.ok(new ApiResponse(true, "登出成功"));
    }

    @GetMapping("/userinfo")
    public ResponseEntity<?> getUserInfo(HttpServletRequest request) {
        String token = jwtTokenProvider.resolveToken(request);
        if (token == null || !jwtTokenProvider.validateToken(token)) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
                    .body(new ApiResponse(false, "无效的令牌"));
        }

        Long userId = jwtTokenProvider.getUserIdFromToken(token);
        User user = userService.findById(userId);

        if (user == null) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
                    .body(new ApiResponse(false, "用户不存在"));
        }

        return ResponseEntity.ok(new ApiResponse(true, "获取成功", new UserInfoResponse(
                jwtTokenProvider.getUserTypeFromToken(token).equals("student") ?
                        String.format("2023%04d", user.getId()) :
                        String.format("T%04d", user.getId()),
                user.getUsername(),
                user.getRole(),
                user.getPic()
        )));
    }
}